import datetime
import json

from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from stw_app import models
from stw_app.consumers import system_notify
from stw_app.decorator import already_login
import requests


def get_longitude_and_latitude(address):
    key = 'af5035a414311145ba566b1d4d9cbab0'
    output = 'json'
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    params = {
        'address': address,
        'key': key,
        'output': output}
    j = json.loads(requests.get(url, params).content)
    Longitude = str(j['geocodes'][1]['location']).split(',')[0]
    Latitude = str(j['geocodes'][1]['location']).split(',')[1]
    return Longitude, Latitude


@csrf_exempt
def get_orders(request):
    if request.method == 'POST':
        # 从前端传入的参数
        selectTypes = request.POST.get('select')
        searchInput = request.POST.get('search')

        # 找到类型为selectTypes和description中包含searchInput的值
        # 从数据库中导入，只选出未确定的值
        orders = models.Order.objects.filter(condition=0).order_by('start_time')
        orders_list = []
        for order in orders:
            print(order.type, selectTypes)
            if selectTypes == '所有' or selectTypes == order.type:
                description = str(order.description)
                if searchInput in description:  # 使用了in，直接判断描述中是否存在
                    orders_list.append({
                        'id': order.id,
                        'customer_id': order.customer_id,
                        'price': order.price,
                        'description': order.description,
                        'type': order.type,
                        'start_time': str(order.start_time)[:-6],
                        'title': order.title,
                        'date': order.date,
                        'duration': order.duration,
                    })
                    print(order.start_time)
        order_json = json.dumps(orders_list)
        # print(order_json)
        return JsonResponse(order_json, content_type='application/json', safe=False)


# 接单
@already_login
@csrf_exempt
def take_order(request):
    if request.method == 'POST':
        # 如果当前用户未登录，则接单失败
        if request.user_obj == None:
            return JsonResponse({'success': False, 'title': '未登录', 'message': '您暂未登录，请登录后再试'})

        # 当前用户已登录
        # 当前用户Id
        id = request.user_obj.id
        # 订单id
        order_id = request.POST.get('order_id')  # 从前端传入的目标订单的Id

        # 向数据库表want_to_worker中插入行
        new_record = {
            'order_id': order_id,
            'want_to_worker_id': id
        }

        # 查询数据库以检查是否存在匹配的行
        matching_rows = models.WantToWorker.objects.filter(**new_record)

        # 如果没有匹配的行，插入新行
        if not matching_rows.exists():
            new_row = models.WantToWorker(**new_record)
            new_row.save()
            try:
                # 向目标用户发送系统通知
                order_obj = models.Order.objects.get(id=order_id)  # 订单对象
                user_obj_sender = models.UserInfo.objects.get(id=id)  # 当前用户对象
                user_obj_receiver = models.UserInfo.objects.get(id=order_obj.customer_id)  # 发单的对象
                system_notify(user_obj_receiver.id,
                              f"用户 {user_obj_sender.name} 向您的订单 {order_obj.title} 发送接单申请！")
            except Exception as e:
                print(e)

        else:
            # 如果有匹配的行，则返回错误
            return JsonResponse({'success': False, 'title': '发送失败', 'message': '您已发送过接单申请，请耐心等待'})
        return JsonResponse({'success': True, 'title': '发送成功', 'message': '接单申请已成功发送'})


#
# # 创建订单
# @already_login
# @csrf_exempt
# def submit_order(request):
#     if request.method == 'POST':
#         # 如果当前用户未登录，则发布订单失败
#         if request.user_obj == None:
#             return JsonResponse({'success': False, 'title': '未登录', 'message': '您暂未登录，请登录后再试'})
#
#         # 当前用户已登录
#         user_id = request.user_obj.id
#         count = models.Order.objects.count()
#         # 表单信息
#         form = request.POST.get('form')
#         form = json.loads(form)
#         print(form)
#         for item in form:
#             if form[item] == '':
#                 return JsonResponse({'success': False, 'title': '提交失败', 'message': '表格不能含空'})
#         start_time, end_time = (datetime.datetime.strptime(date_string[:-1], "%Y-%m-%dT%H:%M:%S.%f") for date_string in
#                                 form['start_end'])
#
#         duration = str((end_time - start_time).total_seconds() / 3600) + 'h'
#         place_name=form['place_name']
#         longitude_1,latitude_1=get_longitude_and_latitude(place_name)
#
#
#         # 向数据库表order中插入新行
#         new_record = models.Order(
#             id = count+1,
#             customer_id = user_id,
#             condition = 0,
#             price = float(form['price']),
#             description = form['description'],
#             type = form['type'],
#             start_time = start_time,
#             end_time = end_time,
#             date = start_time.strftime("%m/%d"),
#             duration = duration,
#             # 这里插入经纬度
#             requirement = form['requirement'],
#             gender_requirement = form['gender_requirement'],
#             # demand = form['demand'], # 等更新表格后插入
#             release_time = datetime.datetime.now(),
#             title = form['title'],
#             longitude=float(longitude_1),
#             latitude=float(latitude_1),
#         )
#         new_record.save()
#         return JsonResponse({'success': True, 'title': '提交成功', 'message': '已成功发布订单'})

# 搜索订单
@csrf_exempt
def search_order(request):
    if request.method == 'POST':
        word = request.POST.get('words')  # 前端将想要搜索的内容放入这里
        results = models.Order.objects.filter(
            Q(description__icontains=word) |
            Q(type__icontains=word) |
            Q(titlerequirement__icontains=word) |
            Q(gender_requirement__icontains=word)
        )
        orders_list = []
        for order in results:
            orders_list.append({
                'id': order.id,
                'customer_id': order.customer_id,
                'price': order.price,
                'description': order.description,
                'type': order.type,
                'start_time': str(order.start_time)[:-6],
                'title': order.title,
                'date': order.date,
                'duration': order.duration,
            })
        order_json = json.dumps(orders_list)
        return JsonResponse(order_json, content_type='application/json', safe=False)


# @already_login
@csrf_exempt
def submit_order(request):
    if request.method == 'POST':
        print("已收到请求")
        user_id = models.Code.objects.filter(id1=3).first().code_1
        # is_active = request.POST.get('is_active')
        # 如果当前用户未登录，则发布订单失败
        # if is_active is not False:
        #     return JsonResponse({'success': False, 'title': '未登录', 'message': '您暂未登录，请登录后再试'})

        count = models.Order.objects.count()
        # 表单信息
        form = request.POST.get('form')
        form = json.loads(form)
        print(form)
        for item in form:
            if form[item] == '':
                return JsonResponse({'success': False, 'title': '提交失败', 'message': '表格不能含空'})
        start_time, end_time = (datetime.datetime.strptime(date_string[:-1], "%Y-%m-%dT%H:%M:%S.%f") for date_string in
                                form['start_end'])

        duration = str((end_time - start_time).total_seconds() / 3600) + 'h'
        place_name = form['place_name']
        longitude_1, latitude_1 = get_longitude_and_latitude(place_name)

        # 向数据库表order中插入新行
        new_record = models.Order(
            id=count + 1,
            customer_id=user_id,
            condition=0,
            price=float(form['price']),
            description=form['description'],
            type=form['type'],
            start_time=start_time,
            end_time=end_time,
            date=start_time.strftime("%m/%d"),
            duration=duration,
            # 这里插入经纬度
            requirement=form['requirement'],
            gender_requirement=form['gender_requirement'],
            demand=form['demand'],  # 等更新表格后插入
            release_time=datetime.datetime.now(),
            title=form['title'],
            longitude=float(longitude_1),
            latitude=float(latitude_1),
        )
        new_record.save()
        print("kanwo")
        return JsonResponse({'success': True, 'title': '提交成功', 'message': '已成功发布订单'})
